package com.mj.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.mj.req.BaseResp;
import com.mj.util.ErrCode;
import com.mj.util.RedisUtil;
import com.mj.util.StringUtil;
import com.mj.util.WxLoginConfigUtil;
import com.mj.util.httpclient.SimpleHttpUtils;

/**
 * 微信登陆
 * 
 * @author majie
 *
 */
@Controller
@RequestMapping("wxLogin")
public class WxLoginController {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 获取微信扫码登陆地址
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getUrl", method = RequestMethod.GET)
	@ResponseBody
	public  BaseResp<String> getWxLoginUrl() {
		logger.info("-------------请求微信扫码地址-------------");
		String state = StringUtil.get32UUID();
		String wxLoginUrl = WxLoginConfigUtil.readConfig("wxlogin");
		String appid = WxLoginConfigUtil.readConfig("appId");
		String url = WxLoginConfigUtil.readConfig("url");
		try {
			url = wxLoginUrl.replace("APPID", appid).replace("REDIRECT_URI", URLEncoder.encode(url, "utf-8"))
					.replace("SCOPE", "snsapi_login").replace("STATE", state);
		} catch (UnsupportedEncodingException e) {
			logger.error("获取扫描地址异常{}",e.getMessage());
			return new BaseResp<>(ErrCode.FAILED,"获取登陆二维码异常");
		}
		return new BaseResp<>(ErrCode.SUCCESS,"success",url);
	}

	/**
	 * 微信扫码登陆回调
	 */
	@RequestMapping(value = "/callBack", method = RequestMethod.GET)
	public void loginCallBack(HttpServletRequest request) {
		logger.info("------------------微信扫码回调------------------");
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		if (StringUtil.isEmpty(code)) {
			logger.error("code获取为空");
			//通过state将用户信息存入redis,取消登录我测试是没有跳转
			RedisUtil.set(state, "该用户禁止微信登陆",5*60);
			return;
		}
		String authInfo = getAuthInfo(code);
		if (StringUtil.isEmpty(authInfo)) {
			logger.error("通过code获取用户信息失败");
			return;
		}
		JSONObject jsonObject = JSONObject.parseObject(authInfo);
		if(!StringUtil.isEmpty(jsonObject.get("errcode"))) {
			logger.error("获取用户信息失败{}",jsonObject.get("errmsg"));
			return;
		}
		String openid = jsonObject.get("openid") + "";
		String access_token = jsonObject.get("access_token") + "";
		String userInfo = getUserInfo(access_token, openid);
		if (StringUtil.isEmpty(authInfo)) {
			logger.error("获取用户信息失败");
			return;
		}
		JSONObject userJson = JSONObject.parseObject(userInfo);
		if(!StringUtil.isEmpty(userJson.get("errcode"))) {
			logger.error("获取用户信息失败{}",jsonObject.get("errmsg"));
			return;
		}
		//通过state将用户信息存入redis
		RedisUtil.set(state, userJson.toJSONString());
	}

	/**
	 * 通过code获取 { "access_token":"ACCESS_TOKEN", "expires_in":7200,
	 * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE",
	 * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" }
	 * 
	 * @return
	 */
	private String getAuthInfo(String code) {
		String getTokenUrl = WxLoginConfigUtil.readConfig("get_acess_token_url");
		String appid = WxLoginConfigUtil.readConfig("appId");
		String secret = WxLoginConfigUtil.readConfig("secret");
		getTokenUrl = getTokenUrl.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
		// 发送请求
		String strJson = SimpleHttpUtils.httpGet(getTokenUrl, new HashMap<String, String>());
		return strJson;
	}

	/**
	 * 通过access_token和openid获取用户信息
	 */

	private String getUserInfo(String access_token, String openid) {
		String getUserInfoUrl = WxLoginConfigUtil.readConfig("get_userInfo_url");
		getUserInfoUrl = getUserInfoUrl.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
		// 发起请求
		String strJson = SimpleHttpUtils.httpGet(getUserInfoUrl, new HashMap<String, String>());
		return strJson;
	}
	
//	/**
//	 * 轮询获取用户信息
//	 * 通过state
//	 * 
//	 * 不该如此设计
//	 */
//	@RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
//	@ResponseBody
//	public BaseResp<String> getUserInfo(HttpServletRequest request) {
//		String state = request.getParameter("state");
//		if(StringUtil.isEmpty(state)) {
//			logger.warn("state为空");
//			return new BaseResp<String>(ErrCode.VALIDATE_FAILED,"state为空");
//		}
//		String userInfo = RedisUtil.get(state);
//		if(StringUtil.isEmpty(userInfo)) {
//			return new BaseResp<String>(ErrCode.FAILED,"用户信息不存在");
//		}
//		//将用户信息改成五分钟以后过期
//		RedisUtil.set(state, userInfo, 5*60);
//		return new BaseResp<String>(ErrCode.SUCCESS,"success",userInfo);
//	}
}
